package com.lianxi.Courses.service.impl;





import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.DictConstant;
import com.lianxi.Courses.constant.StatusConstant;
import com.lianxi.Courses.dao.ChapterMapper;
import com.lianxi.Courses.dao.CourseMapper;
import com.lianxi.Courses.dao.ResourceMapper;
import com.lianxi.Courses.entity.Chapter;
import com.lianxi.Courses.entity.Course;
import com.lianxi.Courses.entity.Resource;
import com.lianxi.Courses.exception.FileDownloadErrorException;
import com.lianxi.Courses.exception.RequestParameterErrorException;
import com.lianxi.Courses.service.ResourceService;
import com.lianxi.Courses.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

/**
 * 翔哥
 * 2025年10月13日
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ChapterMapper chapterMapper;

    @Override
    public PageInfo<Resource> findPage(Resource resource, String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.RESOURCE_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.RESOURCE_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Resource> resources = resourceMapper.selectByParams(resource);

        PageInfo<Resource> resourcePage = new PageInfo<>(resources);
        return resourcePage;
    }

    @Override
    public void updateStatus(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
        if (StatusConstant.RESOURCE_STATUS_ENABLED == resource.getStatus()) {
            resource.setStatus(StatusConstant.RESOURCE_STATUS_DISABLED);
        } else {
            resource.setStatus(StatusConstant.RESOURCE_STATUS_ENABLED);
        }
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    @Override
    public Resource findById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        return resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
    }


    // 在 ResourceService 中添加方法
    @Override
    public void downloadFile(String id, HttpServletResponse response, HttpSession session) throws RequestParameterErrorException, FileDownloadErrorException, UnsupportedEncodingException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
        // 获取文件相对路径
        String relativePath = resource.getPath();

        // 转换为服务器绝对路径
        String realPath = session.getServletContext().getRealPath(relativePath);
        File file = new File(realPath);

        // 检查文件是否存在
        if (!file.exists()) {
            throw new FileDownloadErrorException("文件不存在");
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + java.net.URLEncoder.encode(resource.getOriginalName(), "UTF-8") + "\"");
        response.setHeader("Content-Length", String.valueOf(file.length()));

        // 文件下载

        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        } catch (Exception e) {
            throw new FileDownloadErrorException("文件下载失败");
        }
    }

    @Override
    public Course findByIdForCourse(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Resource resource = resourceMapper.selectByPrimaryKey(Integer.valueOf(id));
        Chapter chapter = chapterMapper.selectByPrimaryKey(resource.getChapterId());
        Course course =courseMapper.selectByPrimaryKey(chapter.getCourseId());

        chapter.setResource(resource);
        course.setChapter(chapter);

        return course;
    }
}
